<template>
  <div class="wrapper">
    <div class="form-wrap">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable"
        :inline="true"
        class="demo-ruleForm"
      >
        <el-form-item label="审核流程名称" prop="name" label-width="120px">
          <el-input v-model="ruleForm.name" style="width: 180px"></el-input>
        </el-form-item>
        <el-form-item label="审核类型" prop="scene_type" label-width="120px">
          <el-select filterable v-model="ruleForm.scene_type">
            <el-option
              v-for="item in typeData"
              :label="item.value"
              :value="item.key"
              :key="item.key + ''"
            >
              {{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="所属大区" prop="branch_id" label-width="120px">
          <el-cascader
            ref="cascader"
            style="width: 100%"
            :options="branchData"
            :show-all-levels="false"
            @change="handleChangeNetwork"
            v-model="ruleForm.branch_id"
            :props="{
              emitPath: false,
              checkStrictly: true,
              label: 'branch_name',
              value: 'id',
              children: 'next_level_data',
            }"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <div>
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            plain
            size="mini"
            @click="handleAddStep"
            >添加
          </el-button>
          <el-button
            style="margin-bottom: 10px"
            type="primary"
            plain
            size="mini"
            @click="handleDelStep"
            >删除
          </el-button>
        </div>

        <el-table
          :data="
            (ruleForm['step'] || []).filter((item) => item.is_deleted !== 1)
          "
          :row-class-name="tableRowClassName"
          @selection-change="handleStepSelectionChange"
          style="width: 100%; margin-bottom: 20px"
          border
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="审核级别" prop="level" width="80">
            <template slot-scope="scope">
              {{ scope.row.level }}
            </template>
          </el-table-column>
          <el-table-column label="步骤名称" prop="name">
            <template slot-scope="scope">
              <el-form-item
                style="margin-top: 16px"
                :prop="'step.' + scope.$index + '.name'"
                :rules="rules.name"
              >
                <el-input v-model="scope.row['name']"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="是否并签" prop="sign_together">
            <template slot-scope="scope">
              <el-form-item
                style="margin-top: 16px"
                :prop="'step.' + scope.$index + '.sign_together'"
                :rules="rules.sign_together"
              >
                <el-select
                  filterable
                  clearable
                  v-model="scope.row.sign_together"
                >
                  <el-option
                    v-for="item in signData"
                    :label="item.value"
                    :value="item.key"
                    :key="item.key + ''"
                  >
                    {{ item.value }}</el-option
                  >
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="审核人" prop="approver">
            <template slot-scope="scope">
              <el-form-item
                filterable
                clearable
                style="margin-top: 16px"
                :prop="'step.' + scope.$index + '.approver'"
                :rules="rules.approver"
              >
                <el-select
                  v-model="scope.row['approver']"
                  filterable
                  multiple
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in approverData"
                    :label="item.name"
                    :value="item.id + ''"
                    :key="item.id + ''"
                    >{{ item.name }}</el-option
                  >
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="抄送人">
            <template slot-scope="scope">
              <el-form-item
                filterable
                clearable
                style="margin-top: 16px"
                :prop="'step.' + scope.$index + '.cpeople'"
              >
                <el-select
                  v-model="scope.row['cpeople']"
                  filterable
                  multiple
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in approverData"
                    :label="item.name"
                    :value="item.id + ''"
                    :key="item.id + ''"
                    >{{ item.name }}</el-option
                  >
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="" width="160">
            <template slot-scope="scope">
              <el-button type="text" @click="handleConditionShow(scope)"
                >设置条件</el-button
              >
              <el-button type="text" @click="handleAddSameStep(scope.row)"
                >增加同一级别</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div
          style="margin-top: 20px; text-align: right; padding-bottom: 20px"
          v-if="!disable"
        >
          <el-button
            :data-tracker="mode === 'add' ? 'P40-6' : 'P40-8'"
            @click="cancelFn"
            >取消</el-button
          >
          <el-button
            :data-tracker="mode === 'add' ? 'P40-5' : 'P40-7'"
            type="primary"
            @click="handleClickSubmit"
            >保存</el-button
          >
        </div>
      </el-form>
      <el-dialog
        title="提示"
        append-to-body
        v-if="dialogVisible"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <!-- <span>这是一段信息</span> -->
        <Condition
          @close="dialogVisible = false"
          :scene_type="this.ruleForm.scene_type"
          :condition_all="currentStep.condition_all"
          @ok="handleSetCondition"
        ></Condition>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { userList } from "@/api/waybill";
import { organizationBox } from "@/api/organization";
import {
  ExamineListFn,
  ExamineCreateFn,
  ExamineDelete,
  ExamineUpdate,
  ExamineDetail,
} from "@/api/auditing";
import Condition from "./condition.vue";
export default {
  name: "auditprocess",
  components: { Condition },
  props: ["mode", "id"],
  data() {
    return {
      ruleForm: {
        branch_id: 0,
        step: [
          {
            level: "1",
            name: "",
            approver: [],
            cpeople: [],
            sign_together: "",
            is_deleted: 0,
          },
        ],
      },
      rules: {
        name: [
          { required: true, message: "请填写审核流程名称", trigger: "blur" },
        ],
        branch_id: [
          { required: true, message: "请选择所属大区", trigger: "change" },
        ],
        scene_type: [
          { required: true, message: "请选择审核类型", trigger: "change" },
        ],
        name: [{ required: true, message: "请填写步骤名称", trigger: "blur" }],
        sign_together: [
          { required: true, message: "请选择是否并签", trigger: "change" },
        ],
        approver: [
          { required: true, message: "请选择审核人", trigger: "change" },
        ],
        cpeople: [
          { required: true, message: "请选择抄送人", trigger: "change" },
        ],
      },
      checkedStep: [],
      stepItem: {
        level: "",
        name: "",
        approver: [],
        sign_together: "",
        cpeople: [],
      },
      branchData: [],
      typeData: [
        {
          key: 1,
          value: "承运商应付审核",
        },
        {
          key: 2,
          value: "报销审核",
        },
        {
          key: 3,
          value: "备用金申请",
        },
        {
          key: 4,
          value: "付款申请",
        },
        {
          key: 5,
          value: "发票申请",
        },
        {
          key: 6,
          value: "合同用章申请",
        },
        {
          key: 7,
          value: "采购申请",
        },
        {
          key: 8,
          value: "中通充值申请",
        },
      ],
      signData: [
        {
          key: 1,
          value: "并签",
        },
        {
          key: 0,
          value: "或签",
        },
      ],
      approverData: [],
      dialogVisible: false,
      currentStep: {},
    };
  },
  computed: {
    disable: function () {
      return this.mode === "detail";
    },
  },
  watch: {
    mode: {
      handler: function (newValue, oldValue) {
        this.handleChangeMode();
      },
      immediate: true,
    },
  },
  mounted() {
    // console.log(this.mode, 'mode--------');
    organizationBox({ not_show_first_branch: 1 }).then((res) => {
      this.branchData = res.data;
      this.branchData.unshift({
        id: 0,
        branch_name: "系统默认",
      });
    });
    userList().then((res) => {
      const data = res.data || [];
      this.approverData = data.map((item) => {
        item.name = item.nickname;
        return item;
      });
    });
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    handleSetCondition(conditions) {
      this.currentStep.condition_all = conditions;
      // console.log(conditions, 'conditions----');
    },
    handleConditionShow(scope) {
      if (!this.ruleForm.scene_type) {
        this.$message({
          message: "请先选择审核类型！",
          type: "warning",
        });
        return;
      }
      this.currentStep = scope.row;
      this.dialogVisible = true;
    },
    handleChangeMode() {
      if (this.mode === "detail" || this.mode === "edit") {
        ExamineDetail({ id: this.id }).then((res) => {
          // console.log(res, 'res-----------');
          const data = res.data;
          // 暂时测试
          // data.step = data.Step;
          this.ruleForm = data;
        });
      } else if (this.mode === "add") {
        Object.assign(this.$data.ruleForm, this.$options.data().ruleForm);
      }
    },
    handleStepSelectionChange(val) {
      this.checkedStep = val.map((item) => item.rowIndex);
    },
    cancelFn() {
      this.$emit("close");
    },
    handleAddStep() {
      const realtyArr = (this.ruleForm.step || []).filter(
        (item) => !(item.is_deleted === 1)
      );
      // const item = JSON.parse(JSON.stringify(this.stepItem));
      const lastStep = realtyArr[realtyArr.length - 1] || { level: 0 };
      this.ruleForm.step = this.ruleForm.step || [];
      this.ruleForm.step.push({
        level: lastStep.level * 1 + 1 + "",
      });
    },
    handleAddSameStep(row) {
      const index = this.ruleForm.step.findIndex(
        (item) => item.rowIndex === row.rowIndex
      );

      this.ruleForm.step.splice(index + 1, 0, {
        level: row.level,
      });
    },
    handleDelStep() {
      for (let i = 0; i < this.checkedStep.length; i++) {
        // 选中的rowindex
        const selectRowIndex = this.checkedStep[i];
        // 页面上展现的数据
        const realtyArr = (this.ruleForm.step || []).filter(
          (item) => !(item.is_deleted === 1)
        );
        // 删除数据操作
        if (this.mode === "add") {
          this.ruleForm.step = (this.ruleForm.step || []).filter(
            (item) => !(selectRowIndex === item.rowIndex)
          );
        } else {
          this.ruleForm.step = this.ruleForm.step.map((item) => {
            if (selectRowIndex === item.rowIndex) {
              item.is_deleted = 1;
            }
            return item;
          });
        }

        // 选中数据的下标
        const delIndex = realtyArr.findIndex(
          (item) => item.rowIndex === selectRowIndex
        );

        const lastStepLevel = (realtyArr[delIndex - 1] || {}).level;
        const delStepLevel = (realtyArr[delIndex] || {}).level;
        const nextStepLevel = (realtyArr[delIndex + 1] || {}).level;
        // 存在同一级别的，跳出当前循环，后边数据level不做处理
        if (delStepLevel === lastStepLevel || delStepLevel === nextStepLevel) {
          continue;
        }
        // 不存在后续数据level－1
        for (let j = delIndex + 1; j < realtyArr.length; j++) {
          const item = realtyArr[j];
          item.level = String(Number(item.level) - 1);
        }
      }

      // if (this.mode === 'add') {
      //     this.ruleForm.step = this.ruleForm.step.filter(item => !this.checkedStep.includes(item.rowIndex));
      // } else {
      //     this.ruleForm.step = this.ruleForm.step.map(item => {
      //         if (this.checkedStep.includes(item.rowIndex)) {
      //             item.is_deleted = 1;
      //         }
      //         return item;
      //     });
      // }
    },
    tableRowClassName(row, index) {
      row.row.rowIndex = row.rowIndex;
      // row.row.level = row.rowIndex + 1 + '';
    },
    handleClickSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        let fn;
        if (this.mode === "add") {
          fn = ExamineCreateFn;
        } else if (this.mode === "edit") {
          fn = ExamineUpdate;
        }
        fn({
          ...this.ruleForm,
          branch_id: this.ruleForm.branch_id
            ? this.ruleForm.branch_id + ""
            : "",
        }).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: this.mode === "add" ? "创建成功" : "修改成功",
              type: "success",
            });
            // console.log(res);
            this.$emit("close", true);
          }
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.form-wrap {
  padding: 20px;
  padding-top: 0;
}
</style>